<template>
  <Layout>
    <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div class="bg-white rounded-lg shadow-md overflow-hidden">
        <div class="px-6 py-4 border-b">
          <h1 class="text-2xl font-bold text-gray-900">编辑个人资料</h1>
        </div>

        <form @submit.prevent="updateProfile" class="p-6 space-y-6">
          <!-- 基本信息 -->
          <div class="space-y-6">
            <h2 class="text-lg font-semibold text-gray-900">基本信息</h2>

            <!-- 头像 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">头像</label>
              <div class="flex items-center space-x-4">
                <img
                  :src="form.avatar_preview || user.avatar || `https://ui-avatars.com/api/?name=${user.name}&size=128`"
                  alt="头像预览"
                  class="w-20 h-20 rounded-full"
                />
                <div>
                  <input
                    type="file"
                    @change="handleAvatarChange"
                    accept="image/*"
                    class="hidden"
                    ref="avatarInput"
                  />
                  <button
                    type="button"
                    @click="$refs.avatarInput.click()"
                    class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300"
                  >
                    更换头像
                  </button>
                  <p class="text-sm text-gray-500 mt-1">支持 JPG、PNG 格式，最大 2MB</p>
                </div>
              </div>
            </div>

            <!-- 姓名 -->
            <div>
              <label for="name" class="block text-sm font-medium text-gray-700 mb-1">姓名</label>
              <input
                id="name"
                v-model="form.name"
                type="text"
                required
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
              />
            </div>

            <!-- 用户名 -->
            <div>
              <label for="username" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
              <input
                id="username"
                v-model="form.username"
                type="text"
                required
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
              />
              <p class="text-sm text-gray-500 mt-1">用户名是你的唯一标识，修改后其他人将无法通过原用户名找到你</p>
            </div>

            <!-- 邮箱 -->
            <div>
              <label for="email" class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
              <input
                id="email"
                v-model="form.email"
                type="email"
                required
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
              />
            </div>

            <!-- 简介 -->
            <div>
              <label for="bio" class="block text-sm font-medium text-gray-700 mb-1">简介</label>
              <textarea
                id="bio"
                v-model="form.bio"
                rows="3"
                maxlength="200"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                placeholder="介绍一下你自己..."
              ></textarea>
              <p class="text-sm text-gray-500 mt-1">{{ form.bio?.length || 0 }}/200</p>
            </div>
          </div>

          <!-- 详细资料 -->
          <div class="space-y-6 pt-6 border-t">
            <h2 class="text-lg font-semibold text-gray-900">详细资料</h2>

            <!-- 位置 -->
            <div>
              <label for="location" class="block text-sm font-medium text-gray-700 mb-1">位置</label>
              <input
                id="location"
                v-model="form.location"
                type="text"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                placeholder="如：北京市"
              />
            </div>

            <!-- 职业 -->
            <div>
              <label for="occupation" class="block text-sm font-medium text-gray-700 mb-1">职业</label>
              <input
                id="occupation"
                v-model="form.occupation"
                type="text"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                placeholder="如：前端工程师"
              />
            </div>

            <!-- 个人网站 -->
            <div>
              <label for="website" class="block text-sm font-medium text-gray-700 mb-1">个人网站</label>
              <input
                id="website"
                v-model="form.website"
                type="url"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                placeholder="https://example.com"
              />
            </div>

            <!-- 详细介绍 -->
            <div>
              <label for="about_me" class="block text-sm font-medium text-gray-700 mb-1">详细介绍</label>
              <textarea
                id="about_me"
                v-model="form.about_me"
                rows="5"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                placeholder="详细介绍你自己，支持 Markdown 格式..."
              ></textarea>
            </div>

            <!-- 技能标签 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">技能标签</label>
              <div class="flex flex-wrap gap-2 mb-2">
                <span
                  v-for="(skill, index) in form.skills"
                  :key="index"
                  class="px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm flex items-center"
                >
                  {{ skill }}
                  <button
                    type="button"
                    @click="removeSkill(index)"
                    class="ml-2 text-blue-600 hover:text-blue-800"
                  >
                    <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                      <path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd" />
                    </svg>
                  </button>
                </span>
              </div>
              <div class="flex space-x-2">
                <input
                  v-model="newSkill"
                  type="text"
                  @keyup.enter="addSkill"
                  class="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                  placeholder="输入技能名称，按回车添加"
                />
                <button
                  type="button"
                  @click="addSkill"
                  class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300"
                >
                  添加
                </button>
              </div>
            </div>
          </div>

          <!-- 社交链接 -->
          <div class="space-y-6 pt-6 border-t">
            <h2 class="text-lg font-semibold text-gray-900">社交链接</h2>

            <!-- GitHub -->
            <div>
              <label for="github" class="block text-sm font-medium text-gray-700 mb-1">GitHub</label>
              <input
                id="github"
                v-model="form.github"
                type="url"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                placeholder="https://github.com/username"
              />
            </div>

            <!-- Twitter -->
            <div>
              <label for="twitter" class="block text-sm font-medium text-gray-700 mb-1">Twitter</label>
              <input
                id="twitter"
                v-model="form.twitter"
                type="url"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                placeholder="https://twitter.com/username"
              />
            </div>

            <!-- LinkedIn -->
            <div>
              <label for="linkedin" class="block text-sm font-medium text-gray-700 mb-1">LinkedIn</label>
              <input
                id="linkedin"
                v-model="form.linkedin"
                type="url"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                placeholder="https://linkedin.com/in/username"
              />
            </div>
          </div>

          <!-- 隐私设置 -->
          <div class="space-y-6 pt-6 border-t">
            <h2 class="text-lg font-semibold text-gray-900">隐私设置</h2>

            <div class="space-y-4">
              <div class="flex items-center">
                <input
                  id="show_email"
                  v-model="form.show_email"
                  type="checkbox"
                  class="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                />
                <label for="show_email" class="ml-2 text-sm text-gray-700">
                  在个人主页显示邮箱地址
                </label>
              </div>

              <div class="flex items-center">
                <input
                  id="allow_message"
                  v-model="form.allow_message"
                  type="checkbox"
                  class="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                />
                <label for="allow_message" class="ml-2 text-sm text-gray-700">
                  允许其他用户给我发送私信
                </label>
              </div>

              <div class="flex items-center">
                <input
                  id="email_notification"
                  v-model="form.email_notification"
                  type="checkbox"
                  class="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                />
                <label for="email_notification" class="ml-2 text-sm text-gray-700">
                  接收邮件通知
                </label>
              </div>
            </div>
          </div>

          <!-- 提交按钮 -->
          <div class="flex justify-end space-x-3 pt-6 border-t">
            <Link
              href="/profile"
              class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300"
            >
              取消
            </Link>
            <button
              type="submit"
              :disabled="loading"
              class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
            >
              {{ loading ? '保存中...' : '保存修改' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </Layout>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Link, router } from '@inertiajs/inertia-vue3'
import Layout from '@/Components/Layout.vue'
import axios from 'axios'

const props = defineProps({
  user: Object
})

const loading = ref(false)
const newSkill = ref('')

const form = reactive({
  name: '',
  username: '',
  email: '',
  bio: '',
  avatar: null,
  avatar_preview: null,
  location: '',
  occupation: '',
  website: '',
  about_me: '',
  skills: [],
  github: '',
  twitter: '',
  linkedin: '',
  show_email: false,
  allow_message: true,
  email_notification: true
})

onMounted(() => {
  // 初始化表单数据
  Object.assign(form, {
    name: props.user.name || '',
    username: props.user.username || '',
    email: props.user.email || '',
    bio: props.user.bio || '',
    location: props.user.location || '',
    occupation: props.user.occupation || '',
    website: props.user.website || '',
    about_me: props.user.about_me || '',
    skills: props.user.skills || [],
    github: props.user.github || '',
    twitter: props.user.twitter || '',
    linkedin: props.user.linkedin || '',
    show_email: props.user.show_email || false,
    allow_message: props.user.allow_message !== false,
    email_notification: props.user.email_notification !== false
  })
})

const handleAvatarChange = (event) => {
  const file = event.target.files[0]
  if (!file) return

  // 验证文件大小
  if (file.size > 2 * 1024 * 1024) {
    alert('文件大小不能超过 2MB')
    return
  }

  // 验证文件类型
  if (!['image/jpeg', 'image/png'].includes(file.type)) {
    alert('只支持 JPG 和 PNG 格式')
    return
  }

  form.avatar = file

  // 预览图片
  const reader = new FileReader()
  reader.onload = (e) => {
    form.avatar_preview = e.target.result
  }
  reader.readAsDataURL(file)
}

const addSkill = () => {
  if (!newSkill.value.trim()) return
  if (form.skills.includes(newSkill.value)) {
    alert('该技能已存在')
    return
  }
  if (form.skills.length >= 10) {
    alert('最多添加10个技能标签')
    return
  }

  form.skills.push(newSkill.value.trim())
  newSkill.value = ''
}

const removeSkill = (index) => {
  form.skills.splice(index, 1)
}

const updateProfile = async () => {
  loading.value = true

  try {
    const formData = new FormData()

    // 添加所有表单字段
    Object.keys(form).forEach(key => {
      if (key === 'avatar' && form[key]) {
        formData.append('avatar', form[key])
      } else if (key === 'skills') {
        formData.append('skills', JSON.stringify(form[key]))
      } else if (key !== 'avatar_preview') {
        formData.append(key, form[key])
      }
    })

    await axios.post('/profile/update', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    // 成功后跳转到个人主页
    router.visit('/profile')
  } catch (error) {
    console.error('更新失败:', error)
    alert('保存失败，请稍后重试')
  } finally {
    loading.value = false
  }
}
</script>